package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomerException;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.DishFlavor;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private DishMapper dishMapper;


    @Override
    @Transactional(rollbackFor = Exception.class) //开启事务
    public void saveWithDishFlavor(DishDto dishDto) {
        //1. 先保存菜品（只有向保存菜品，才会生成菜品id）
        this.save(dishDto); //保存之前，id没有值，保存之后，id有值（雪花算法）

        //2. 再保存口味集合（保存口味之前，需要先关联菜品id）
        List<DishFlavor> flavors = dishDto.getFlavors();
        //给每个口味对象的dishId属性赋值，dishDto的id
        flavors.forEach(f -> f.setDishId(dishDto.getId()));
        //批量保存
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public Page<DishDto> pageDishDto(Integer page, Integer pageSize, String name) {
        // dishMapper肯定要自定义方法查询（需要我们分页？？？）
        Page<DishDto> pageInfo = new Page<>(page, pageSize);
        return dishMapper.pageDishDto(pageInfo, name);
    }

    @Override
    public DishDto getByIdWithFlavor(Long id) {
        return dishMapper.getByIdWithFlavor(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateWithFlavor(DishDto dishDto) {
        //1. 修改菜品表dish
        this.updateById(dishDto);

        //2. 修改口味表dish_flavor（先删再加？为什么）
        // delete from dish_flavor where dish_id=?
        dishFlavorService.lambdaUpdate() //lambdaUpdate()可以更新，也可以删除操作
                .eq(DishFlavor::getDishId, dishDto.getId()) //条件部分
                .remove(); //删除操作

        //批量添加口味，给每个口味对象的dishId属性赋值，dishDto的id
        dishDto.getFlavors().forEach(f -> f.setDishId(dishDto.getId()));
        dishFlavorService.saveBatch(dishDto.getFlavors());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByIds(Long[] ids) {

        //0. select count(*) from  dish where id in ( ) and status=1
        Integer count = this.lambdaQuery()
                .eq(Dish::getStatus, 1)
                .in(Dish::getId, Arrays.asList(ids))
                .count();
        if (count > 0) {
            //不能删除
            throw new CustomerException("有菜品正在售卖，不能删除！");
        }

        //1. delete from dish where id in ( )
        this.removeByIds(Arrays.asList(ids));

        //2. delete from dish_flavor where dish_id in ( )
        dishFlavorService.lambdaUpdate()
                .in(DishFlavor::getDishId, Arrays.asList(ids))
                .remove();

    }

    @Override
    public List<DishDto> listDishDto(Dish dish) {
        return dishMapper.listDishDto(dish);
    }

    @Override
    public List<DishDto> setmealDishDto(Long setmealId) {
        return dishMapper.setmealDishDto(setmealId);
    }
}


